from flask_mail import Message
from exts import mail
from celery import Celery
import logging
from logging.handlers import RotatingFileHandler

# 设置日志
logger = logging.getLogger('celery_task')
# 在 Celery 配置文件或模块中设置
broker_connection_retry_on_startup = True
# 定义任务函数
def send_mail(recipient, subject, body):
    """发送邮件的函数

    参数:
        recipient (str): 收件人邮箱地址
        subject (str): 邮件主题
        body (str): 邮件正文

    返回:
        dict: 邮件发送状态，包含成功或失败的信息
    """
    message = Message(subject=subject, recipients=[recipient], body=body)
    try:
        mail.send(message)
        return {"status": "SUCCESS"}
    except Exception as e:
        return {"status": "FAILURE","Exception":str(e)}



# 创建celery对象工厂函数
def make_celery(app):
    celery = Celery(app.import_name, backend=app.config['CELERY_RESULT_BACKEND'],
                    broker=app.config['CELERY_BROKER_URL'])
    TaskBase = celery.Task

    # 定义一个抽象类 ContextTask，继承自 TaskBase
    class ContextTask(TaskBase):
        # 表示该类是一个抽象类
        abstract = True
        def __call__(self, *args, **kwargs):
            # 重写 __call__ 方法，以便在应用程序上下文中调用任务
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)

    celery.Task = ContextTask
    app.celery = celery

    # 添加任务
    celery.task(name="send_mail")(send_mail)

    # 设置日志
    handler = RotatingFileHandler('celery_worker.log', maxBytes=10000000, backupCount=5)
    formatter = logging.Formatter('[%(asctime)s: %(levelname)s/%(processName)s] %(message)s')
    handler.setFormatter(formatter)
    handler.setLevel(logging.INFO)

    logger = logging.getLogger('celery')
    logger.addHandler(handler)
    logger.setLevel(logging.INFO)

    return celery
